package com.skeeey.aim.listener;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.io.FileUtils;

import com.skeeey.aim.util.AIMUtil;

public class CleanListener implements ServletContextListener {
	private static final long PERIOD = 24L * 60 * 60 * 1000;
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		// do nothing
		
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				String[] tempPaths = {AIMUtil.getSystemConfig("vin.image.temp.path"),
						AIMUtil.getSystemConfig("zip.temp.path"),
						AIMUtil.getSystemConfig("execl.temp.path")};
				for(String tempPath : tempPaths) {
					if(tempPath != null) {
						File tempDir = new File(tempPath);
						if(tempDir.exists() && tempDir.isDirectory()) {
							try {
								FileUtils.deleteDirectory(tempDir);
								System.out.println("[AIM Info]Deleted the temporary directory :" + tempPath + " at <" + new Date() + ">");
								tempDir.mkdirs();
							} catch (IOException e) {
								//do nothing
							}
						} else {
							tempDir.mkdirs();
						}
					}
				}
			}
		};
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 1); // 1:00AM 
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date firstTime = calendar.getTime();
		Timer timer = new Timer();
		timer.schedule(task, firstTime, PERIOD);
	}

}
